import { authFailed, JWT_SECRET_KEY, parseJson, parseUser, response } from "../utils"
import users from '../models/user'
import jwt from 'jsonwebtoken'

const TOKEN_TIMEOUT = 60 * 60 // Token 1小时过期

export default [
  {
    url: '/api/auth/login',
    method: 'post',
    timeout: 300, // 模拟响应延时
    rawResponse: async(req, res) => {
      const body = await parseJson(req)
      const user = users.find(item => item.username === body.username)
      if(!user){
        return authFailed(res, "用户不存在")
      }
      if(user.password !== body.password){
        return authFailed(res, "密码错误")
      }
      const payload = {
        id: user.id,
        username: user.username,
        exp: Math.floor(Date.now()/1000) + TOKEN_TIMEOUT,
      }
      const token = jwt.sign(payload, JWT_SECRET_KEY, {algorithm: 'HS256'})
      return response(res, {token: token})
    }
  },
  {
    url: '/api/auth/userinfo',
    method: 'get',
    rawResponse: (req, res) => {
      const user = parseUser(req.headers)
      if(!user){return authFailed(res, "Token过期")}
      return response(res, user)
    }
  },
  {
    url: '/api/auth/logout',
    method: 'post',
  }
]